package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import server.clients.ClientList;

public class HttpServer {
	private static int port;
	private static ClientList clientList = new ClientList();
	
	public static void main(String args[]) {
		Configuration conf = new Configuration();
		int cport = Integer.parseInt(conf.getProperty("PORT"));
		String aPort = conf.getProperty("APORT");
		String aIp = conf.getProperty("AIP");
		int[] ports = new int[100];
		for (int i=0; i<100;ports[i]=cport+i++);
		ServerSocket server_socket;
		try {
			server_socket = create(ports);
			port = server_socket.getLocalPort();
//			OnlinePeers oPeers = new OnlinePeers(clientList);
//			oPeers.start();
			newConnection nc = new newConnection(conf.getProperty("PORT"), Integer.toString(port), aPort, aIp);
			nc.start();
			System.out.println("httpServer running on port " + server_socket.getLocalPort());
			while (true) {
				Socket socket = server_socket.accept();
				httpRequestHandler request = new httpRequestHandler(socket);
				Thread thread = new Thread(request);
				thread.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static ServerSocket create(int[] ports) throws IOException {
	    for (int port : ports) {
	        try {
	            return new ServerSocket(port);
	        } catch (IOException ex) {
	            continue; // try next port
	        }
	    }

	    // if the program gets here, no port in the range was found
	    throw new IOException("no free port found");
	}

	public static int getPort() {
		return port;
	}

	public static ClientList getClientList() {
		return clientList;
	}

}

